<template>
  <div>
    <h1 style="margin:10px  0">
      <el-row>
        <el-col :span="19">
          <span>添加活动</span>
          
        </el-col>
        <el-col :span="5" style="text-align:right">
          <i class="el-icon-error" style="background:#e6e6e6" @click="goBack"></i>
        </el-col>
      </el-row>
    </h1>
    <div>
      
     <el-form  label-width="80px"  ref="formAling" :rules="rules"  :model="formLabelAlign">
       <el-form-item label="活动名:" prop="name">
          <el-input v-model="formLabelAlign.name" style="width:80%"></el-input>
        </el-form-item>
        <el-form-item label="时间"  prop="begin_time">
          <el-date-picker v-model="formLabelAlign.begin_time" type="date"  format="yyyy 年 MM 月 dd 日" value-format="timestamp" placeholder="选择日期"></el-date-picker> 至
          <el-date-picker v-model="formLabelAlign.end_time" type="date" format="yyyy 年 MM 月 dd 日" value-format="timestamp" placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="活动地址">
            <el-select v-model="ruleForm2.province"  @change="changeCity" filterable placeholder="选择省份" style="width:110px">
              <el-option v-for="item in ruleForm2.options1" :key="item.id" :label="item.areaname" :value="item.id" > </el-option>
            </el-select>
            <el-select v-model="ruleForm2.city" @change="changeArea" filterable placeholder="选择城市" style="width:110px">
              <el-option v-for="item in ruleForm2.options2" :key="item.id" :label="item.areaname" :value="item.id"> </el-option>
            </el-select>
            <el-select v-model="ruleForm2.area" @change="changeVal" filterable placeholder="选择区" style="width:110px">
              <el-option v-for="item in ruleForm2.options3" :key="item.id" :label="item.areaname" :value="item.id"> </el-option>
            </el-select>
          </el-form-item>
        <el-form-item label="详细地址:" prop="position">
          <el-input  v-model="formLabelAlign.positaion" @blur="getLng" style="width:80%"></el-input>
          <div>
            <span>{{address}}</span>
            <span v-if="okLng== 1" style="margin-left:20px;color:#67c23a">经纬度获取成功</span>
            <span v-else-if="okLng== 2" style="margin-left:20px;color:red">无法获取该得知的经纬度获取</span>
            <span v-else></span>
          </div>
        </el-form-item>
       
        <el-form-item label="封面图:" prop="logo_url" style="width:60%">
          <div>
              <el-upload 
                class="avatar-uploaderInfo"
                action="https://upload.qiniup.com/"
                :show-file-list="false"
                :on-success="handleOkLogo"
                :before-upload="beforeAvatarUpload"
                :data="postData">
                <img v-if="formLabelAlign.logo_url" :src="formLabelAlign.logo_url" class="avatarInfo">
                <i v-else class="el-icon-plus avatar-uploader-iconInfo"></i>
              </el-upload>
          </div>
        </el-form-item>
        <div> 
          <squill-editor-qiniu :token='postData.token' :tinymceHtml="formLabelAlign.content" v-model="formLabelAlign.content"  uploadUrl='https://upload.qiniup.com/'></squill-editor-qiniu>
        </div>

        <el-form-item >
        <div style="color:#ccc;margin:10px 0">信息提交后，牙记将1-2个工作日内完成审核</div>

          <el-row style="width:60%">
            <el-col :span="12"><el-button type="warning"  @click="submitArticle(1)">保 存</el-button></el-col>
            <el-col :span="12"><el-button type="primary" @click="submitArticle(0)">提交审核</el-button></el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </div>
    <div v-show="!showMap" id="XSDFXPage" class="XSDFXPage"></div>
  </div>
</template>

<script>
import Http from '@/Http/Http'
import SquillEditorQiniu from '../../Doctors/Hositem/quill-editor-qiniu';

export default {
  props:['editData'],
  components:{
    SquillEditorQiniu
  },
  data () {
    const name = (rule,value,callback) => {
      if (value === '') {
        callback(new Error('请输入活动标题'))
      } else {
        callback()
      }
    }
    const begin_time = (rule,value,callback) => {
      if (this.formLabelAlign.begin_time === '' || this.formLabelAlign.end_time === '' ) {
        callback(new Error('请选输入开始时间、结束时间'))
      } else {
        callback()
      }
    }
    const price = (rule,value,callback) => {
      if (this.formLabelAlign.price === '' || this.formLabelAlign.originalPrice === '') {
        callback(new Error('请输入价格、原价'))
      } else {
        callback()
      }
    }

    const positaion =(rule,value,callback) => {
      if (value === '') {
        callback(new Error('请填写详情地址'))
      } else {
        callback()
      }
    }

    const logo_url = (rule,value,callback) => {
      if (value === '') {
        callback(new Error('请上传图标'))
      } else {
        callback()
      }
    }
    
    return {
      postData:{
        token:'',
        key:'fily',
      },
      showMap:true,//是否显示地图
      address:'',//获取的地址
      okLng:0, //状态
      ruleForm2: {       
        options1:[],
        options2:[],
        options3:[],
        province:'',//省
        city:'',//市
        area:'',//区
      },
      mapdata:{ //地址的经纬度
        lat:'',
        lng:''
      },
      dialogVisible: false,
      options:'',
      getAreaOk:false,
      tokenimgUrl:'', //存储域名
      formLabelAlign:{
        file_url: [],
        name:'',
        link_url:'',
        logo_url:'',
        positaion:'',
        content:'',
        begin_time:'',
        end_time:''
      },
      
      fileList:[],
      rules:{
        name:[
          {validator:name,trigger:'blur'}
        ],
        begin_time:[
          {validator:begin_time,trigger:'blur'}
        ],
        positaion:[
          {validator:positaion,trigger:'blur'}
        ],
        logo_url:[
          {validator:logo_url,trigger:'change'}
        ],
      },
    }
    
  },

  computed: {
  },
  watch:{
    'getAreaOk':function(){
      //console.log('watch')
    }
  },
  mounted() {
           
      // 百度地图API功能
      // 创建Map实例
      this.map = new BMap.Map("XSDFXPage",{enableMapClick:true});
      this.map.centerAndZoom("深圳",12);           
      this.map.enableScrollWheelZoom();    //启用滚轮放大缩小，默认禁用
      this.map.enableContinuousZoom();    //启用地图惯性拖拽，默认禁用

      this.map.addControl(new BMap.NavigationControl());  //添加默认缩放平移控件
      this.map.addControl(new BMap.OverviewMapControl()); //添加默认缩略地图控件
      this.map.addControl(new BMap.OverviewMapControl({ isOpen: true, anchor: BMAP_ANCHOR_BOTTOM_RIGHT }));   //右下角，打开

      this.localSearch = new BMap.LocalSearch(this.map);
      this.localSearch.enableAutoViewport(); //允许自动调节窗体大小
      
    //this.map.addEventListener("click", this.showInfo);
  },
  created() {
    Http.getAreaList(0)
    .then( res => {
      this.ruleForm2.options1 = res.data.data;
    })
    this.getToken()
    if (this.editData) {
     this.formLabelAlign.name = this.editData.name;
     this.formLabelAlign.begin_time = this.editData.begin_time;
     this.formLabelAlign.end_time = this.editData.end_time;
     this.formLabelAlign.positaion = this.editData.positaion;
     this.formLabelAlign.link_url = this.editData.link_url;
     this.formLabelAlign.content = this.editData.content;
     this.formLabelAlign.file_url = this.editData.files;
     this.formLabelAlign.logo_url = this.editData.logo_url;
     this.ruleForm2.province = this.editData.province_id;
     if(this.editData.province_id){
        this.changeCity(this.editData.province_id,this.editData.city_id)
      }
      if(this.editData.city_id){
        this.changeArea(this.editData.city_id,this.editData.area_id)
      }
    }else {
      this.addGetInfo()
    }
  },
  methods:{
    getToken() {
      Http.QiniuToken({})
      .then( res => {
        this.postData.token = res.data.data.uptoken;
        this.tokenimgUrl = res.data.data.domain
      })
      .catch( error => {
        this.$message.error('服务器请求失败，请重新登录')
        console.log(error)
      })
      
    },
    addGetInfo(){

      
          Http.getHospitaInfo()
          .then( res => {
            this.formLabelAlign.positaion = res.data.data.position;
            this.ruleForm2.province = res.data.data.province_id;
            if(res.data.data.province_id){
              this.changeCity(res.data.data.province_id,res.data.data.city_id)
            }
            if(res.data.data.city_id){
              this.changeArea(res.data.data.city_id,res.data.data.area_id)
            }
          
            //this.ruleForm2.area = res.data.data.area_id;
          })
          .catch( error => {
            //this.$router.push('/')
            console.log(error)
          })
        
    },
     changeCity(val,city=''){
      this.okLng = 0;
      Http.getAreaList(val)
        .then( res => {
          this.ruleForm2.options2 = res.data.data;
          this.ruleForm2.city = city;
        })
    },
    changeArea(val,are=''){
      this.okLng = 0;
      Http.getAreaList(val)
        .then( res => {
          this.ruleForm2.area = are;
          this.ruleForm2.options3 = res.data.data;
          if(!this.getAreaOk){
            setTimeout(()=>{
              this.getLng()
              console.log(222222)
            },50)
          }
          this.getAreaOk = true;
          
        })
    },
    changeVal(val){
      this.okLng = 0;
    },
    getLng() {
      let a,b,c;
      this.ruleForm2.options1.forEach(item => {
        if(item.id == this.ruleForm2.province){
          a = item.areaname
        }
      })
      if(this.ruleForm2.options2){
         this.ruleForm2.options2.forEach(item => {
          if(item.id == this.ruleForm2.city){
            b = item.areaname
          }
        })
      }
      if(this.ruleForm2.options3){
        this.ruleForm2.options3.forEach(item => {
          if(item.id == this.ruleForm2.area){
            c = item.areaname
          }
        })
      }
      console.log(a,b,c)
      if(!a || !b || !c){
        this.$message.error('请选择省，市，区');
        return
      }
      this.address = `${a}${b}${c}${this.formLabelAlign.positaion}`;
      this.searchByStationName()

    },
    searchByStationName() {
      this.okLng = 0;    
      this.map.clearOverlays();//清空原来的标注
      var keyword = this.address;
      const _this = this;
      this.localSearch.setSearchCompleteCallback(function (searchResult) {
          
          var poi = searchResult.getPoi(0);
          
          if(!poi){
            _this.okLng = 2;
            return
          }
          _this.vala = poi.point.lng + "," + poi.point.lat;
          _this.mapdata.lng = poi.point.lng;
          _this.mapdata.lat = poi.point.lat;
          if(_this.mapdata.lng){
            _this.okLng = 1;
          } else {
            _this.okLng = 2;
          }
          // console.log(_this.mapdata)
          _this.map.centerAndZoom(poi.point, 13);
          var marker = new BMap.Marker(new BMap.Point(poi.point.lng, poi.point.lat));  // 创建标注，为要查询的地方对应的经纬度
          _this.map.addOverlay(marker);
          var content = _this.aderss + "<br/><br/>经度：" + poi.point.lng + "<br/>纬度：" + poi.point.lat;
          var infoWindow = new BMap.InfoWindow("<p style='font-size:14px;'>" + content + "</p>");
          marker.addEventListener("click", function () { this.openInfoWindow(infoWindow); });
          // marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
      });
      _this.localSearch.search(keyword);
    },
    handleRemoveLogo(file, fileList) {
      console.log(file, fileList);
    },
    beforeAvatarUpload(file) {
       const isLt2M = file.size / 1024 / 1024 < 10;
       if(!isLt2M) {
         this.$message.error('上传的文件大小不能大于10MB!');
         return
       }
      this.postData.key = file.name
      console.log('预期',file)
    },
    handleOkLogo(responed) {
      this.formLabelAlign.logo_url = `http://${this.tokenimgUrl}/${responed.hash}`;
      console.log('上传图片',this.formLabelAlign.file_url)
    },
   
    submitArticle(val) {
      
      const content = this.formLabelAlign.content.replace('<img','<img style="width:100%"')
      const param = {
        "is_draft":val,
        "name":this.formLabelAlign.name,  //活动标题
        "begin_time":this.formLabelAlign.begin_time,  //开始时间
        "end_time":this.formLabelAlign.end_time,  //介绍时间 
        "positaion":this.formLabelAlign.positaion, // 位置  
        "area_id":this.ruleForm2.area, //区
        "city_id":this.ruleForm2.city, //市
        "province_id":this.ruleForm2.province, //省
        "lng":this.mapdata.lng,
        "lat":this.mapdata.lat,
        "link_url":this.formLabelAlign.link_url, //链接
        "content":content, //内容
        "files":this.formLabelAlign.file_url,
        "logo_url":this.formLabelAlign.logo_url //封面
      };
      this.$refs['formAling'].validate((valid) => {
        if (valid) {
          if(!this.formLabelAlign.content){
            this.$message.error('请输入活动内容')
            return
          };
          this.editData ? this.editFun(param,val) : this.addFun(param,val);
        } else {
          this.$message.error('信息不完整')
        }
      })
    },
    deletFun(row){
      console.log(123333)
    },
    addFun(obj,val){
       Http.addActivityInsert(obj)
      .then( res => {
        if ( res.data.code == 200) {
         if(val==0){
           this.$message.success('提交成功，请耐心等候审核状态')
          }else if (val ==1 ){
            this.$message.success('保存成功')
          }
          this.goBack()
        } else {
            this.$message.error('操作失败')
        }
      })
    },
    imgStr(val) {
      const index = val.split('http://pdi2rfi8n.bkt.clouddn.com/');
      return index[1]
    },
    editFun(obj,val) {
      obj.id = this.editData.id,
      Http.editActivity(obj)
      .then( res => {
        if ( res.data.code == 200) {
          if(val==0){
           this.$message.success('提交成功，请耐心等候审核状态')
          }else if (val ==1 ){
            this.$message.success('保存成功')
          }

          this.goBack()
        } else {
          this.$message.error('操作失败')
        }
      })
    },
    goBack(){
      this.formLabelAlign.name = "";
      this.formLabelAlign.begin_time = "";
      this.formLabelAlign.end_time = "";
      this.formLabelAlign.positaion = "";
      this.formLabelAlign.link_url = "";
      this.$emit('getlist');
    },
  }
}
</script>
<style>

.avatar-uploader-iconInfo {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatarInfo {
    width: 178px;
    height: 178px;
    display: block;
  }
  .avatar-uploaderInfo .el-upload {
  border: 1px dashed #d9d9d9!important;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
</style>
